# coding:utf-8

from rest_framework.views import exception_handler
from rest_framework.response import Response

ERROR_CODES = {
    0: 'success',
    # 权限相关
    1000: '身份认证信息未提供',
    1002: '权限不足',
    # 实体相关
    2000: '实体数据未找到',
    2001: '图片素材字段不正确',
    2002: '素材type不正确',
    2003: '图片上传失败, 请重试',
    # 制作素材
    3000: '查询关键字缺失',
}


class MeException(Exception):
    code = None
    msg = None

    def __init__(self, code, msg=None):
        super(MeException, self).__init__()
        self.code = code
        if msg:
            self.msg = msg
        else:
            self.msg = ERROR_CODES.get(self.code, '未知异常')


def me_exception_handler(exc, context):
    response = exception_handler(exc, context)  # 获取本来应该返回的exception的response
    if response is None:
        response = Response(exception=exc)
    if isinstance(exc, MeException):
        response.data = {
            'code': exc.code,
            'msg': exc.msg
        }
    elif isinstance(exc, Exception):
        response.data = {
            'code': 3000,
            'msg': exc.__str__()
        }
    else:
        response.data = {
            'code': response.status_code,
            'msg': response.data['detail'] if response.data else ''
        }
    return response


def get_object_or_404(model, pk):
    try:
        return model.objects.get(pk=pk)
    except model.DoesNotExist:
        raise MeException(2000)


def assert_and_exception(v1, v2, code, msg=None):
    if v1 != v2:
        raise MeException(code, msg)


def equal_and_exception(v1, v2, code, msg=None):
    if v1 == v2:
        raise MeException(code, msg)


def has_obj_permission(user, obj):
    assert_and_exception(user, obj.user, 1000)


def valid_and_exception(form, code):
    res = form.is_valid()
    assert_and_exception(res, True, code, form.error_messages)
